package com.css.zfzx.sjcj.modules.hddcTargetRegion.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.entity.HddcGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.HddcTargetregionNativeRepository;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.HddcTargetregionRepository;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.entity.HddcTargetregionEntity;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.service.HddcTargetregionService;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.viewobjects.HddcTargetregionQueryParams;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.viewobjects.HddcTargetregionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcTargetregionServiceImpl implements HddcTargetregionService {

	@Autowired
    private HddcTargetregionRepository hddcTargetregionRepository;
    @Autowired
    private HddcTargetregionNativeRepository hddcTargetregionNativeRepository;

    @Override
    public JSONObject queryHddcTargetregions(HddcTargetregionQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcTargetregionEntity> hddcTargetregionPage = this.hddcTargetregionNativeRepository.queryHddcTargetregions(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcTargetregionPage);
        return jsonObject;
    }


    @Override
    public HddcTargetregionEntity getHddcTargetregion(String id) {
        HddcTargetregionEntity hddcTargetregion = this.hddcTargetregionRepository.findById(id).orElse(null);
         return hddcTargetregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcTargetregionEntity saveHddcTargetregion(HddcTargetregionEntity hddcTargetregion) {
        String uuid = UUIDGenerator.getUUID();
        hddcTargetregion.setUuid(uuid);
        hddcTargetregion.setCreateUser(PlatformSessionUtils.getUserId());
        hddcTargetregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcTargetregion.setIsValid("1");
        hddcTargetregion.setQualityinspectionStatus("0");
        hddcTargetregion.setExtends10("1");
        this.hddcTargetregionRepository.save(hddcTargetregion);
        return hddcTargetregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcTargetregionEntity> saveHddcTargetregionList(List<HddcTargetregionEntity> list) {
        for (HddcTargetregionEntity hddcTargetregion : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcTargetregion.setUuid(uuid);
            hddcTargetregion.setCreateUser(PlatformSessionUtils.getUserId());
            hddcTargetregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcTargetregion.setIsValid("1");
            hddcTargetregion.setQualityinspectionStatus("0");
            hddcTargetregion.setExtends10("1");
        }

        return hddcTargetregionNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcTargetregionEntity updateHddcTargetregion(HddcTargetregionEntity hddcTargetregion) {
        HddcTargetregionEntity entity = hddcTargetregionRepository.findById(hddcTargetregion.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcTargetregion);
        hddcTargetregion.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcTargetregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcTargetregionRepository.save(hddcTargetregion);
        return hddcTargetregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcTargetregions(List<String> ids) {
        List<HddcTargetregionEntity> hddcTargetregionList = this.hddcTargetregionRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcTargetregionList) && hddcTargetregionList.size() > 0) {
            for(HddcTargetregionEntity hddcTargetregion : hddcTargetregionList) {
                hddcTargetregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcTargetregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcTargetregion.setIsValid("0");
                this.hddcTargetregionRepository.save(hddcTargetregion);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcTargetregionEntity> hddcTargetregionList = this.hddcTargetregionRepository.queryHddcTargetregionsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcTargetregionList) && hddcTargetregionList.size() > 0) {
            for(HddcTargetregionEntity hddcTargetregion : hddcTargetregionList) {
                hddcTargetregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcTargetregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcTargetregion.setIsValid("0");
                this.hddcTargetregionRepository.save(hddcTargetregion);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcTargetregionEntity> hddcTargetregionList = this.hddcTargetregionRepository.queryHddcTargetregionsByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcTargetregionList) && hddcTargetregionList.size() > 0) {
            for(HddcTargetregionEntity hddcTargetregion : hddcTargetregionList) {
                hddcTargetregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcTargetregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcTargetregion.setIsValid("0");
                this.hddcTargetregionRepository.save(hddcTargetregion);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("WorkRegionID")){
            str+="WorkRegionID,";
        }
        if(!set.contains("Name")){
            str+="Name,";
        }
        if(!set.contains("TargetName")){
            str+="TargetName,";
        }
        if(!set.contains("TRArea")){
            str+="TRArea,";
        }
        if(!set.contains("MappingArea")){
            str+="MappingArea,";
        }
        if(!set.contains("TRFaultCount")){
            str+="TRFaultCount,";
        }
        if(!set.contains("TRStudiedFaultCount")){
            str+="TRStudiedFaultCount,";
        }
        if(!set.contains("AFaultCount")){
            str+="AFaultCount,";
        }
        if(!set.contains("RSProcess")){
            str+="RSProcess,";
        }
        if(!set.contains("FieldSvyPtCount")){
            str+="FieldSvyPtCount,";
        }
        if(!set.contains("TrenchCount")){
            str+="TrenchCount,";
        }
        if(!set.contains("TrenchVolume")){
            str+="TrenchVolume,";
        }
        if(!set.contains("DrillCount")){
            str+="DrillCount,";
        }
        if(!set.contains("DrillLength")){
            str+="DrillLength,";
        }
        if(!set.contains("GPhWellCount")){
            str+="GPhWellCount,";
        }
        if(!set.contains("CollectedSampleCount")){
            str+="CollectedSampleCount,";
        }
        if(!set.contains("SampleCount")){
            str+="SampleCount,";
        }
        if(!set.contains("DatingSampleCount")){
            str+="DatingSampleCount,";
        }
        if(!set.contains("GeomorphySvyProjectCount")){
            str+="GeomorphySvyProjectCount,";
        }
        if(!set.contains("SeismicProjectCount")){
            str+="SeismicProjectCount,";
        }
        if(!set.contains("CrustalDfmProjectCount")){
            str+="CrustalDfmProjectCount,";
        }
        if(!set.contains("GeophysicalSvyProjectCount")){
            str+="GeophysicalSvyProjectCount,";
        }
        if(!set.contains("GeochemicalProjectCount")){
            str+="GeochemicalProjectCount,";
        }
        if(!set.contains("IsVolcanic")){
            str+="IsVolcanic,";
        }
        if(!set.contains("SRA")){
            str+="SRA,";
        }
        if(!set.contains("SDA")){
            str+="SDA,";
        }
        if(!set.contains("NumSimulationCount")){
            str+="NumSimulationCount,";
        }
        if(!set.contains("Description")){
            str+="Description,";
        }
        if(!set.contains("ShowCode")){
            str+="ShowCode,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }

        return str;
    }

    @Override
    public void saveHddcTargetregionFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcTargetregionEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcTargetregionEntity data = new HddcTargetregionEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setWorkregionid(obs.get(2).toString());
                data.setName(obs.get(3).toString());
                data.setTargetname(obs.get(4).toString());
                data.setTrarea(Integer.valueOf(obs.get(5).toString()));
                data.setMappingarea(Integer.valueOf(obs.get(6).toString()));
                data.setTrfaultcount(Integer.valueOf(obs.get(7).toString()));
                data.setTrstudiedfaultcount(Integer.valueOf(obs.get(8).toString()));
                data.setAfaultcount(Integer.valueOf(obs.get(9).toString()));
                data.setRsprocess(Integer.valueOf(obs.get(10).toString()));
                data.setFieldsvyptcount(Integer.valueOf(obs.get(11).toString()));
                data.setTrenchcount(Integer.valueOf(obs.get(12).toString()));
                data.setTrenchvolume(Double.valueOf(obs.get(13).toString()));
                data.setDrillcount(Integer.valueOf(obs.get(14).toString()));
                data.setDrilllength(Integer.valueOf(obs.get(15).toString()));
                data.setGphwellcount(Integer.valueOf(obs.get(16).toString()));
                data.setCollectedsamplecount(Integer.valueOf(obs.get(17).toString()));
                data.setSamplecount(Integer.valueOf(obs.get(18).toString()));
                data.setDatingsamplecount(Integer.valueOf(obs.get(19).toString()));
                data.setGeophysicalsvyprojectcount(Integer.valueOf(obs.get(20).toString()));
                data.setSeismicprojectcount(Integer.valueOf(obs.get(21).toString()));
                data.setCrustaldfmprojectcount(Integer.valueOf(obs.get(22).toString()));
                data.setGeophysicalsvyprojectcount(Integer.valueOf(obs.get(23).toString()));
                data.setGeochemicalprojectcount(Integer.valueOf(obs.get(24).toString()));
                data.setIsvolcanic(Integer.valueOf(obs.get(25).toString()));
                data.setSra(Integer.valueOf(obs.get(26).toString()));
                data.setSda(Integer.valueOf(obs.get(27).toString()));
                data.setNumsimulationcount(Integer.valueOf(obs.get(28).toString()));
                data.setDescription(obs.get(29).toString());
                data.setShowcode(obs.get(30).toString());
                data.setCommentInfo(obs.get(31).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);

            saveHddcTargetregionList(datas);
        }
    }

    @Override
    public List<HddcTargetregionEntity> findAll() {
        List<HddcTargetregionEntity> list=this.hddcTargetregionRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcTargetregionRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcTargetregionEntity> hddcTargetregionList = this.hddcTargetregionRepository.queryHddcTargetregionByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcTargetregionList) && hddcTargetregionList.size() > 0) {
            hddcTargetregionRepository.deleteAll(hddcTargetregionList);
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcTargetregionQueryParams queryParams, HttpServletResponse response) {
        List<HddcTargetregionEntity> yhDisasterEntities = hddcTargetregionNativeRepository.exportYhDisasters(queryParams);
        List<HddcTargetregionVO> list=new ArrayList<>();
        for (HddcTargetregionEntity entity:yhDisasterEntities) {
            HddcTargetregionVO yhDisasterVO=new HddcTargetregionVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"目标区-面","目标区-面",HddcTargetregionVO.class,"目标区-面.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcTargetregionVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcTargetregionVO.class, params);
            List<HddcTargetregionVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcTargetregionVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcTargetregionVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcTargetregionVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcTargetregionEntity yhDisasterEntity = new HddcTargetregionEntity();
            HddcTargetregionVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcTargetregion(yhDisasterEntity);
        }
    }
}
